package com.example.demo.config.quartz;

import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.example.demo.entity.quartz.QuartzEntity;
import com.example.demo.quartz.dao.QuartzManagerDao;

/**
 * 在项目启动的时候创建一个定时任务
 * @author xzw
 *
 */
@Component
public class TaskRunner implements ApplicationRunner{
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private QuartzManagerDao quartzManagerDao;
	
	@Autowired
	private Scheduler scheduler;

	@Override
	public void run(ApplicationArguments args) throws Exception {
		
		List<QuartzEntity> quartzs = quartzManagerDao.queryQuartzJobList(null);
		
		int quartzNum = quartzs.size();
		//如果没有创建的定时任务则创建一个
		if(0==quartzNum) {
			logger.info("初始化测试job");
			QuartzEntity quartz = new QuartzEntity();
			quartz.setJobName("test01");
			quartz.setJobGroup("test");
			quartz.setDescription("测试任务");
			quartz.setJobClassName("com.example.demo.quartz.job.ChickenJob");
			quartz.setCronExpression("*/5 * * * * ?");
			quartz.setJobMethodName("test1");
			Class cls = Class.forName(quartz.getJobClassName());
			cls.newInstance();
			//构建job信息
			JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
							quartz.getJobGroup()).withDescription(quartz.getDescription()).build();
			
			job.getJobDataMap().put("jobMethodName", "test1");
			
			CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
			//触发时间点
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartz.getJobName(),quartz.getJobGroup())
							.startNow().withSchedule(cronScheduleBuilder).build();
			
			scheduler.scheduleJob(job,trigger);
		}
	}

}
